package com.aaa.service.impl;


import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.aaa.config.IdGeneratorSnowflake;
import com.aaa.dao.UserDao;
import com.aaa.entity.CheckItem;
import com.aaa.entity.User;
import com.aaa.service.UserService;
import com.aaa.util.AccountName;
import com.aaa.util.JwtUtil;
import com.aaa.util.WebUtil;
import com.aaa.vo.Result;
import com.aaa.vo.UserVo;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Override
    public User findByUsername(String username) {
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("phone",username);
        wrapper.eq("status",0);
        return userDao.selectOne(wrapper);
    }

    @Override
    public Result<User> getInfo() {
        String token = WebUtil.getRequest().getHeader("token");
        Map<String, Object> tokenInfo = JwtUtil.getTokenChaim(token);

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",tokenInfo.get("username"));
        wrapper.eq("status",0);
        User user = userDao.selectOne(wrapper);


        return new Result<>(2000,"ok", user);
    }

    @Override
    public Result<IPage<User>> searchUser(Integer currentPage, Integer pageSize, UserVo userVo) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        Page<User> page = new Page<>(currentPage,pageSize);
        if(StringUtils.hasText(userVo.getUserName())){
            wrapper.like("user_name",userVo.getUserName());
        }
        System.out.println("是否有查询手机号码=========== = " + userVo.getPhone());
        if(StringUtils.hasText(userVo.getPhone())){
            wrapper.eq("phone",userVo.getPhone());
        }
        if(Objects.nonNull(userVo.getDeptId())){
            wrapper.eq("dept_id",userVo.getDeptId());
        }
        if(Objects.nonNull(userVo.getStatus())){
            wrapper.eq("status",userVo.getStatus());
        }
        if(Objects.nonNull(userVo.getDateRange())&&userVo.getDateRange().length==2){
            wrapper.between("create_time",userVo.getDateRange()[0],userVo.getDateRange()[1]);
        }
        IPage<User> page1 = userDao.selectPage(page,wrapper);
        
        return new Result<>(2000,"查询用户",page1);
    }

    @Override
    public List<User> queryUserNeedScheduling(Map<String, Object> map) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(map.get("userId"))){
            userQueryWrapper.eq("user_id",map.get("userId"));
        }
        if (Objects.nonNull(map.get("deptId"))){
            userQueryWrapper.eq("dept_id",map.get("deptId"));
        }
        userQueryWrapper.eq("status",0);
        userQueryWrapper.eq("scheduling_flag",0);
        return userDao.selectList(userQueryWrapper);
    }

    @Override
    public List<User> initUser() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        return userDao.selectList(wrapper);
    }

    @Override
    public User queryUserByPhone(Long phone) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0);
        wrapper.eq("phone",phone);
        return userDao.selectOne(wrapper);
    }
    @Resource
    private IdGeneratorSnowflake idGeneratorSnowflake;

    @Override
    public Result<String> reg(User user) {
        //确认码
        long l = idGeneratorSnowflake.snowflakeId();
        //盐
        String salt = RandomUtil.randomString(6);
        //加密密码 :原密码+盐
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(encode);

        //初始化账号
        //新增账号

        return null;
    }

    @Autowired
    private AccountName accountName;
    @Override
    public Result<String> addOrUpdUser(User user) {
        String userName = accountName.getAccountName();
        System.out.println("添加或修改的====================== " + user);
        int num;
        if (user.getUserId()!=null){
            user.setUpdateBy(userName);
            user.setUpdateTime(new Date());
            //修改
            num = userDao.updateById(user);
        }else {
            user.setCreateBy(userName);
            user.setCreateTime(new Date());
            num = userDao.insert(user);
        }
        if (num>0){
            return Result.success();
        }
        return Result.error();
    }

    @Override
    public Result<User> queryById(Long id) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0);
        wrapper.eq("user_id",id);
        User user = userDao.selectOne(wrapper);
        return new Result<>(2000,"ok",user);
    }
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public Result<String> loginOut() {
        String token = WebUtil.getRequest().getHeader("token");
        try {
            Boolean token1 = redisTemplate.delete(token);
            System.out.println("token1 = " + token1);
            if (token1){
                return new Result<>(2000,"ok");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
       return null;
    }

    @Override
    public Result<String> add() {
        Long bd = redisTemplate.opsForValue().increment("bd");//操作字符串
        System.out.println("bd = " + bd);
        return null;
    }


    @Override
    public Result<String> updPass(String oldPass, String newPass) {
        BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
        User user = accountName.getUser();
        boolean matches1 = bc.matches(oldPass, user.getPassword());
        System.out.println("是否比对成功 = " + matches1);
        String encode = bc.encode(newPass);
        User user1 = new User();
        user1.setUserId(user.getUserId());
        if (matches1){
            user1.setPassword(encode);
            int i = userDao.updateById(user1);
            if (i>0){
                return Result.success();
            }
        }
        return Result.error();
    }

    @Override
    public Result<String> retPass(Long[] uid) {
        System.out.println("重置用户的id = " + Arrays.toString(uid));

        BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
        String defPass = bc.encode("888888");
//        List<Long> collect1 = Arrays.stream(uid).collect(Collectors.toList());
        for (Long aLong : uid) {
            User user = new User();
            user.setUserId(aLong);
            user.setPassword(defPass);
            userDao.updateById(user);
        }
        return Result.success();
//        User user = new User();
//        user.setUserId(uid);
//        user.setPassword(defPass);
//
//        if (i>0){
//           return Result.success();
//        }
//        return Result.error();
    }


    public static void main(String[] args) {


//        String oldPass="123456";
//        String newPass="123456";
//        //盐  fd13ez
//        String salt = RandomUtil.randomString(6);      //fd13ez
////        System.out.println("salt = " + salt);
//        //加密密码 :原密码+盐
//        BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
//        String encode1 = bc.encode(newPass+"fd13ez");
//        boolean matches1 = bc.matches(newPass, encode1);
//        System.out.println("matches = " + matches1);
        String oldPass="123456";
        String newPass="123456";
        BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
        String encode1 = bc.encode(oldPass);
//        User user = accountName.getUser();
        boolean matches = bc.matches(oldPass, "$2a$10$1L8eHUFq4IOa04Vvdv5lg.oJnZtFeipQrEdHTq.Sp1d6UySYlQ5Ta");
        System.out.println("是否比对成功 = " + matches);
        if (matches){

        }



    }
}






